package com.openatc.agent.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.openatc.agent.service.AscsDao;
import com.openatc.agent.service.GenericMsgStrategy;
import com.openatc.comm.data.MessageData;
import com.openatc.core.model.RESTRet;
import com.openatc.core.util.RESTRetUtils;
import com.openatc.model.model.AscsBaseModel;
import com.openatc.model.model.ControlPattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * @Classname SetPhaseDwell
 * @Description
 * @Date 2022/7/19 14:06
 * @Created by panleilei
 */
@Service(value = "control/pattern-14")
public class PhaseDwell extends GenericMsgStrategy {
    @Autowired
    private AscsDao devDao;

    @Override
    public RESTRet preProcess(MessageData requestData) {
        JsonElement data = requestData.getData();
        ControlPattern controlPattern = gson.fromJson(data, ControlPattern.class);

        convertDwellToPhaseLock(controlPattern,requestData.getAgentid());
        requestData.setData(gson.toJsonTree(controlPattern));

        return RESTRetUtils.successObj(null);
    }

    /**
     * 相位驻留转换为相位锁定
     * @param controlPattern
     * @param agentid
     */
    private void convertDwellToPhaseLock(ControlPattern controlPattern, String agentid) {
        // 只处理ocp协议的相位驻留
        AscsBaseModel dev = devDao.getAscsByID(agentid);
        if (!"ocp".equals(dev.getProtocol())) return;

        int value = controlPattern.getValue();
        // value为0时下发恢复自主控制指令
        if (value == 0) {
            controlPattern.setControl(0);
        }
        // value非0时下发相位锁定指令
        else {
            controlPattern.setControl(22);
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("greenflash",3);
            jsonObject.addProperty("yellow",3);
            jsonObject.addProperty("redclear",1);
            jsonObject.addProperty("mingreen",15);
            jsonObject.addProperty("duration",controlPattern.getDuration());

            JsonArray jsonArray = new JsonArray();
            JsonObject jsonObject1 = new JsonObject();
            jsonObject1.addProperty("id",value);
            jsonObject1.addProperty("type",1);
            jsonArray.add(jsonObject1);

            jsonObject.add("phases",jsonArray);
            controlPattern.setData(jsonObject);
        }

    }
}
